package com.itphy.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itphy.pojo.SysArea;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class JSONTree {
    private Map<String,JSONObject> data=new HashMap();
    private JSONArray tree=new JSONArray();

    /**
     * 必须按照父子顺序增加
     * @param sysArea
     */
    public void put(SysArea sysArea){
        JSONObject item=new JSONObject();
        String key=keyGen(sysArea);
        if(Integer.parseInt(sysArea.getLevels())==1){
            item.put("value", sysArea.getAreaCode());
            item.put("label", sysArea.getAreaName());
            item.put("children", new JSONArray());
            data.put(key, item);
            tree.add(item);
        }else{
            item.put("value", sysArea.getAreaCode());
            item.put("label", sysArea.getAreaName());
            item.put("children", new JSONArray());
            data.put(key, item);
            putTree(key,item);
        }
    }

    //生成key
    private String keyGen(SysArea sysArea){
        String key=sysArea.getLevelOne();
        if(Integer.parseInt(sysArea.getLevelTwo())!=0){
            key+="_"+sysArea.getLevelTwo();
        }
        if(Integer.parseInt(sysArea.getLevelThree())!=0){
            key+="_"+sysArea.getLevelThree();
        }
        return key;
    }

    //拼接节点
    private void putTree(String key,JSONObject obj){
        try {
            String parentKey=key.substring(0,key.lastIndexOf("_"));
            JSONObject c=data.get(parentKey);
            if(Objects.isNull(c)){
                putTree(parentKey, obj);
            }else {
                ((JSONArray)c.get("children")).add(obj);
            }
        }catch (Exception e){
            System.out.println("异常数据::  "+ obj);
        }
    }

    public String toJsonString(){
        return tree.toJSONString();
    }

    public Map<String, JSONObject> getData() {
        return data;
    }

    public void setData(Map<String, JSONObject> data) {
        this.data = data;
    }

    public JSONArray getTree() {
        return tree;
    }

    public void setTree(JSONArray tree) {
        this.tree = tree;
    }
}
